#include <string.h>
#include <stdlib.h>

#include "tick.h"
#include "timer.h"
#include "package.h"
#include "battery.h"
#include "hardware.h"
#include "BatteryMonitorADC.h"


#undef TRACE_LEVEL
#undef TRACE_TITLE
#undef TRACE_TITLE
#define TRACE_LEVEL TRACE_LEVEL_DEBUG
#define TRACE_NAME  TRACE_NAME_DISABLE
#define TRACE_TITLE "BETTRY"
#include "trace.h"


#define DEFAULT_BATTARY_MONITOR_PERIOD_MS	10000

static int CheckBatteryReadPeriodInMs = DEFAULT_BATTARY_MONITOR_PERIOD_MS;
static uint32_t LastReadTimeMark = 0;

void BatteryMonitorInit(int ReadPeriodInMs) {
	GPIO_InitTypeDef GPIO_InitStructure;
	
	// Config GPIO as input floating
	GPIO_InitStructure.GPIO_Pin = BATTERY_MONITOR_PIN;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
	GPIO_Init(BATTERY_MONITOR_PORT, &GPIO_InitStructure);
	
	SetBatteryMonitorPeriodInMs(ReadPeriodInMs);
	BetteryMonitorADCInit();
	LastReadTimeMark = get_tick_count();
}

int OutBatterySensorData() {
	uint16_t buffer;
	uint32_t tick;
	
	tick = get_tick_count();
	if((tick - LastReadTimeMark) > CheckBatteryReadPeriodInMs) {
		LastReadTimeMark = tick;
		ReadBerrtyADCValue(&buffer);
		TRACE_DEBUG("Bettry ADC Value: %d, Volt: %0.1f", buffer, 
			(float)buffer * 6.6 / 4096.0);
		WritePackage(PKG_BATTERY_DATA, tick, &buffer, 1);
	}
	return 0;
}

void BatteryMonitorDeInit() {
	BetteryMonitorADCDeInit();
}

int SetBatteryMonitorPeriodInMs(int ms) {
	if(ms < 0)
		ms = DEFAULT_BATTARY_MONITOR_PERIOD_MS;
	CheckBatteryReadPeriodInMs = ms;
	return 0;
}


